package com.lanhao.aot.carrierintegration.colissimo;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import javax.activation.DataHandler;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.colissimo.shipment.Bordereau;
import com.colissimo.shipment.BordereauResponse;
import com.colissimo.shipment.GenerateLabel;
import com.colissimo.shipment.GenerateLabelV2ResponseType;
import com.colissimo.shipment.LabelV2Response;
import com.colissimo.shipment.Message;
import com.colissimo.shipment.ServiceSlsV2WS;
import com.colissimo.shipment.SlsServiceWS_002f20;
import com.lanhao.aot.carrierintegration.commondto.LabelApplyRequestDTO;
import com.lanhao.aot.util.DateUtil;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpRequest;

public class ColissimoUtil {
	private static final Logger LOG = LoggerFactory.getLogger(ColissimoUtil.class);
	public static final String ContractNumber_1 = "950631";
	public static final String ContractNumber_2 = "950632";
	public static final String Password = "Asendia##2020";
	public static final String CountryCode = "FR";
	public static final String URL = "http://47.254.176.63/carrier/proxy/colissimo";

	public static void main(String[] args) {
//		String result = getColissimoProxyInvoke();
//		LabelRemoteGetResponse proxyResp = JSON.parseObject(result, LabelRemoteGetResponse.class);
//		String templateContent = proxyResp.getLabelUrl();
//		String labelNo = proxyResp.getLabelNo();
//		String filePath = "D:/" + UUID.fastUUID().toString() + ".pdf";
//		Base64.decodeToFile(templateContent, new File(filePath));
//		proxyResp.setLabelUrl(filePath);
//		System.out.println("返回结果信息labelNo=" + labelNo + "|proxyResp=" + JSON.toJSONString(proxyResp));
		
		fileToBytes();
	}
	
	public static String getColissimoProxyInvoke() {
		LabelApplyRequestDTO request = new LabelApplyRequestDTO();
		request.setFromFirm("Kun Zhou");
		request.setFromAddress1("mon adresse");
		request.setFromCountryCode("FR");
		request.setFromCity("Paris");
		request.setFromZip5("75007");
		
		request.setToName("Alibaba");
		request.setToAddress1("mon adresseadresse");
		request.setToCountryCode("FR");
		request.setToCity("Paris");
		request.setToZip5("75007");
		long start = System.currentTimeMillis();
		String result = HttpRequest.post(URL).body(JSON.toJSONString(request)).timeout(10000).execute().body();
		long end = System.currentTimeMillis();
		LOG.info("获取colissimo信息，url={},request={}，耗时={}ms", URL, JSON.toJSONString(request), (end - start));
		return result;
	}
	
	
	public void doColissionInvoke() {
		SlsServiceWS_002f20 slsService = new SlsServiceWS_002f20();
		ServiceSlsV2WS port = slsService.getSlsServiceV2WSPort();
		GenerateLabel.GenerateLabelRequest request = new GenerateLabel.GenerateLabelRequest();
		request.setContractNumber(ContractNumber_1);
		request.setPassword(Password);
		GenerateLabel.GenerateLabelRequest.OutputFormat outputFormat = new GenerateLabel.GenerateLabelRequest.OutputFormat();
		outputFormat.setX(0);
		outputFormat.setY(0);
		outputFormat.setOutputPrintingType("PDF_10x15_300dpi"); // PDF_A4_300dpi 太大了，暂时不用
		request.setOutputFormat(outputFormat);
		GenerateLabel.GenerateLabelRequest.Letter letter = new GenerateLabel.GenerateLabelRequest.Letter();

		GenerateLabel.GenerateLabelRequest.Letter.Service service = new GenerateLabel.GenerateLabelRequest.Letter.Service();
		service.setProductCode("CORE");
		service.setDepositDate(DateUtil.convertToXMLGregorianCalendar(new Date()));
		letter.setService(service);

		GenerateLabel.GenerateLabelRequest.Letter.Parcel parcel = new GenerateLabel.GenerateLabelRequest.Letter.Parcel();
		parcel.setWeight(3f); // kg
		letter.setParcel(parcel);

		GenerateLabel.GenerateLabelRequest.Letter.Sender sender = new GenerateLabel.GenerateLabelRequest.Letter.Sender();
		sender.setSenderParcelRef("senderParcelRef");

		GenerateLabel.GenerateLabelRequest.Letter.Sender.Address senderAddress = new GenerateLabel.GenerateLabelRequest.Letter.Sender.Address();
		senderAddress.setCompanyName("Kun Zhou");
//		senderAddress.setLastName("Kun");
//		senderAddress.setFirstName("Zhou");
		senderAddress.setLine0("line0");  // Floor, corridor, stairwell, flat number.
		senderAddress.setLine1("line1"); // Entrance, building, residence.
		senderAddress.setLine2("mon adresse"); // Number and street name.
		senderAddress.setLine3("line3"); // Named place or other mention.
		senderAddress.setCountryCode(CountryCode);
		senderAddress.setCity("Paris");
		senderAddress.setZipCode("75007");
		sender.setAddress(senderAddress);
		letter.setSender(sender);

		GenerateLabel.GenerateLabelRequest.Letter.Addressee addressee = new GenerateLabel.GenerateLabelRequest.Letter.Addressee();
//		addressee.setAddresseeParcelRef("addresseeParcelRef");
		GenerateLabel.GenerateLabelRequest.Letter.Addressee.Address receiveAddress = new GenerateLabel.GenerateLabelRequest.Letter.Addressee.Address();
		receiveAddress.setCompanyName("Alibaba");
		receiveAddress.setLine0("line8888");
		receiveAddress.setLine1("line8888");
		receiveAddress.setLine2("mon adresseadresse");
		receiveAddress.setLine3("line8888");
		receiveAddress.setCountryCode(CountryCode);
		receiveAddress.setCity("Paris");
		receiveAddress.setZipCode("75007");
		addressee.setAddress(receiveAddress);

		letter.setAddressee(addressee);

		request.setLetter(letter);
		System.out.println("请求参数：" + JSON.toJSONString(request));
		GenerateLabelV2ResponseType generateLabelResp = port.generateLabel(request);
		System.out.println("响应参数：" + JSON.toJSONString(generateLabelResp));
		List<Message> messages = generateLabelResp.getMessages();
		if (messages == null || messages.size() == 0) {
			System.out.println("返回message信息：" + JSON.toJSONString(messages));
			return;
		}
		Message message = messages.get(0);
		String messageType = message.getType();
		String messageContent = message.getMessageContent();
		if ("ERROR".equals(messageType)) {
			System.out.println("请求失败了，原因：" + messageContent);
			return;
		}
		LabelV2Response labelV2Response = generateLabelResp.getLabelV2Response();
		String parcelNumber = labelV2Response.getParcelNumber();
		DataHandler labelHandler = labelV2Response.getLabel();
		try {
			InputStream source = labelHandler.getInputStream();
			FileUtils.copyInputStreamToFile(source, new File("D:/" + UUID.fastUUID().toString() + ".pdf"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("parcelNumber=" + parcelNumber);
		FileUtil.writeString(JSON.toJSONString(labelV2Response), new File("D:/response_colissimo_json.txt"), "UTF-8");
	}
	
	
	 
    /**
     * 将Byte数组转换成文件
     * @param bytes    byte数组
    //* @param filePath 文件路径  如 D://test/ 最后“/”结尾
     */
    public static void fileToBytes() {
    	
    	
    	SlsServiceWS_002f20 slsService = new SlsServiceWS_002f20();
		ServiceSlsV2WS port = slsService.getSlsServiceV2WSPort();
	
		com.colissimo.shipment.GenerateBordereauByParcelsNumbers.GenerateBordereauParcelNumberList generateBordereauParcelNumberList = new com.colissimo.shipment.GenerateBordereauByParcelsNumbers.GenerateBordereauParcelNumberList(); 
		generateBordereauParcelNumberList.getParcelsNumbers().add("8R45191092601");
		BordereauResponse r = port.generateBordereauByParcelsNumbers(ContractNumber_1, Password, generateBordereauParcelNumberList);
		
//		BordereauResponse r = port.getBordereauByNumber(ContractNumber_1, Password, "8R45191092601");
		List<Message> messages = r.getMessages();
		System.out.println(JSON.toJSONString(messages));
		Bordereau bordereau = r.getBordereau();
		byte[] bytes = bordereau.getBordereauDataHandler();
		
        //文件名
        String name = "D:/aaa.pdf";
 
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
 
            file = new File(name);
            if (!file.getParentFile().exists()) {
                //文件夹不存在 生成
                file.getParentFile().mkdirs();
            }
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
